// @ts-ignore
import { MP4Clip } from "../../@webav/av-cliper/dist/av-cliper.js";
function getBolbUrl(file: File): Promise<string> {
  return new Promise((resolve) => {
    let reader = new FileReader();
    reader.readAsArrayBuffer(file);
    reader.onload = (e: ProgressEvent<FileReader>) => {
      resolve(URL.createObjectURL(new Blob([e.target!.result!])));
    };
  });
}

function getBase64Image(vf: VideoFrame) {
  let canvas = document.createElement("canvas");
  canvas.width = vf.codedWidth;
  canvas.height = vf.codedHeight;
  let ctx = canvas.getContext("2d");
  ctx!.drawImage(vf, 0, 0, vf.codedWidth, vf.codedHeight);

  return canvas.toDataURL("image/png");
}

async function clipTick(clip: MP4Clip, time: number = 0) {
  const { video } = await clip.tick(time);
  let result = getBase64Image(video!);
  video!.close();
  return URL.createObjectURL(dataURLtoBlob(result));
}

function dataURLtoBlob(dataurl: string) {
  let arr = dataurl.split(","); //分割为数组，分割到第一个逗号
  let mime = arr[0].match(/:(.*?);/)![1]; //获取分割后的base64前缀中的类型
  let bstr = window.atob(arr[1]);
  let n = bstr.length;
  let u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime }); //文件类型格式
}
export { getBolbUrl, getBase64Image, clipTick };
